<template>
	<div @mouseover="handleMouseover" @mouseout="showUpload = false" class="ui-upload-image" :style="{width: width +'px', height: actualHeight +'px'}">
		<div class="ui-image" v-show="value">
			<img :src="imageUrl" />
		</div>
		<div class="ui-progress" v-show="uploading">
			<Progress :percent="percent" hide-info></Progress>
		</div>
		<div class="ui-upload" v-show="showUpload || !value">
			<Upload
		        ref="upload"
		        type="drag"
                accept="image/*"
		        :action="ajax"
                :headers="headers"
		        :show-upload-list="false"
		        :format="format"
		        :max-size="maxSize"
		        :before-upload="handleBeforeUpload"
		        :on-success="handleSuccess"
		        :on-format-error="handleFormatError"
		        :on-exceeded-size="handleMaxSize"
		        :on-progress="handleProgress"
		        :multiple="false"
		    >
		    	<div :style="{'line-height': actualHeight - 2 + 'px'}">
		            <Icon type="md-camera" size="20"></Icon>
		       	</div>
		    </Upload>
	    </div>
	</div>
</template>

<script>
import Cookies from 'js-cookie';
import { host } from '@/config/index';
export default {
    name: 'ImageUpload',
	props: {
		width: {										// 组件宽度
			type: Number,
			default: 60
		},
        height: {										// 组件宽度
        	type: Number,
        	default: 0
        },
		format: {										// 图片格式
			type: Array,
			default: function() {
				return ['jpg','jpeg','png', 'gif', 'bmp'];
			}
		},
		maxSize: {										// 图片大小限制，KB为单位
			type: Number,
			default: 2048
		},
		banUpload: {									// 禁止上传，只做展示
			type: Boolean,
			default: false
		},
		value: String									// 默认图片地址
	},
	data() {
		return {
			ajax: host + '/attachmentApi/upload',
            showUpload: false,
            uploading: false,
            uploadList: [],
            percent: 0,
            imageUrl: '',
            headers: {}
		}
	},
    computed: {
        actualHeight() {
            return this.height > 0 ? this.height : this.width;
        }
    },
	methods: {
        handleSuccess (res, file, fileList) {
        	this.percent = 100;
        	this.imageUrl = res.data.full_url;
        	this.$emit('input', res.data.full_url);
            this.$emit('on-change', res.data);
        	setTimeout(() => {
        		this.uploading = false;
        		this.percent = 0;
        	}, 300)
        },
        handleFormatError (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: file.name + ' 的格式不正确， 请选择'+ this.format.join('、') +'格式的文件。'
            });
			setTimeout(() => {
				this.uploading = false;
				this.percent = 0;
			}, 300)
        },
        handleMaxSize (file) {
        	// 单位换算
        	let _Mb = this.maxSize / 1024;
        	let f = _Mb.toString().split(".");
        	if(f.length > 1) {
        		_Mb = f[0] + '.' + f[1].substring(0, 2);
        	}
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: file.name + ' 文件太大了， 请选择'+ _Mb +'M以内的文件。'
            });
        },
        handleBeforeUpload () {
        	this.percent = 0;
        	this.uploading = true;
        },
        handleProgress(event, file, fileList) {
        	this.percent = file.percentage;
        },
        handleMouseover() {
        	if(!this.uploading && !this.banUpload){
        		this.showUpload = true;
        	}
        }
    },
    mounted() {
        if(Cookies.get('token')) {
            this.headers.Authorization = Cookies.get('token');
        }
    	this.imageUrl = this.value;
    },
    watch: {
    	value(newVal, oldVal) {
    		if(this.imageUrl != newVal){
    			this.imageUrl = newVal;
    		}
    	}
    }
}
</script>

<style scoped>
.ui-upload-image {
    position: relative;
    display: inline-block;
    box-sizing: border-box;
    border: 1px dashed #dddee1;
    border-radius: 4px;
    background-color: #fff;
    vertical-align: top;
    overflow: hidden;
}
.ui-upload-image:hover {
	border-color: #2d8cf0;
}
.ui-upload-image .ui-image {
	position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
	z-index: 1;
}
.ui-upload-image .ui-image img {
    max-width: 100%;
    max-height: 100%;
}
.ui-upload-image .ui-upload, .ui-upload-image .ui-progress {
	position: absolute;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	background-color: rgba(255, 255, 255, .8);
	z-index: 2;
}
.ui-upload-image .ui-progress > div {
	position: absolute;
	left: 3px;
	right: 3px;
	top: 50%;
	margin-top: -5px;
	width: auto;
    line-height: 1;
}
.ui-upload-image .ui-upload > div > div {
	border: 0;
	border-radius: 0;
	background-color: transparent;
}
</style>